import React, { Suspense } from 'react';
import { Navigate, useRoutes } from 'react-router-dom';
import BasicLayout from '@/layout/BasicLayout';

const Login = React.lazy(() => import('@/pages/Login/index.jsx'));
const NotFound = React.lazy(() => import('@/pages/NotFound/index.jsx'));
const Home = React.lazy(() => import('@/pages/Home/index.jsx'));
const UserManager = React.lazy(() => import('@/pages/UserManage/index.jsx'));

function getSuspense(element) {
  return <Suspense>{element}</Suspense>;
}

// 默认路由
const defaultRoute = {
  title: '首页',
  key: 'default',
  pathname: '/app/home',
  children: getSuspense(<Home />)
};

// 路由配置
const routeList = [
  { path: '/', label: '首页', element: <Navigate to="/app/home" /> },
  {
    path: '/login',
    label: '登录',
    element: <Login />,
    auth: false
  },
  {
    path: '/404',
    label: '404',
    element: <NotFound />,
    auth: false
  },
  {
    path: '/app',
    label: '控制台',
    element: <BasicLayout />,
    isLazy: false,
    children: [
      {
        path: 'home',
        label: '首页',
        element: <Home />
      },
      {
        path: 'user-manager',
        label: '用户管理',
        element: <UserManager />
      }
    ]
  },
  { path: '*', label: '404', element: <Navigate to="/404" />, auth: false }
];

function renderRoutes(routeList) {
  function replaceLazyRoute(list) {
    list.forEach((item) => {
      if (item.element && item.isLazy !== false) {
        item.element = getSuspense(item.element);
      }
      if (item.children) {
        replaceLazyRoute(item.children);
      }
    });
  }

  replaceLazyRoute(routeList);

  return routeList;
}

function GetRoutes() {
  return useRoutes(renderRoutes(routeList));
}

export { GetRoutes, routeList, defaultRoute };
